<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Model\Article;
use App\Model\ArticleAction;
use Request;
use Redirect;

class ArticleActionController extends Controller
{
  public function index()
  {
    return Redirect::to('/');
  }

  public function store(Request $request)
  {
    $action = $request::get("action","");
    $score = $request::get("score",0);
    $article_id = $request::get("article_id",0);
    $user = auth()->user();

    $article = Article::findOrFail($article_id);
    if(!$article){
      return  ['error'=>1,'message'=>'文章未找到！'];
    }

    switch($action)
    {
      //赞
      case "turn-up":
        $action_up = ArticleAction::where('user_id',$user->id)->where('article_id',$article_id)->where('action','turn-up')->first();
        if($action_up){
          ArticleAction::destroy($action_up->id);
          return  ['error'=>0,'message'=>'点赞已取消！'];
        } else {
          $action_up = ArticleAction::create([
            'user_id' => $user->id,
            'action' => $action,
            'score' => 1,
            'article_id' => $article_id,
          ]);
          $action_down = ArticleAction::where('user_id',$user->id)->where('article_id',$article_id)->where('action','turn-down')->first();
          if($action_down){
            ArticleAction::destroy($action_down->id);
          }
        }
        return  ['error'=>0,'message'=>'点赞成功！'];
        break;
      //踩
      case "turn-down":
        $action_down = ArticleAction::where('user_id',$user->id)->where('article_id',$article_id)->where('action','turn-down')->first();
        if($action_down){
          ArticleAction::destroy($action_down->id);
          return  ['error'=>0,'message'=>'踩已取消！'];
        } else {
          $action_down = ArticleAction::create([
            'user_id' => $user->id,
            'action' => $action,
            'score' => -1,
            'article_id' => $article_id,
          ]);
          $action_up = ArticleAction::where('user_id',$user->id)->where('article_id',$article_id)->where('action','turn-up')->first();
          if($action_up){
            ArticleAction::destroy($action_up->id);
          }
        }
        return  ['error'=>0,'message'=>'你狠狠踩了一脚！'];
        break;
      //打分
      case "turn-score":
          $action_score = ArticleAction::where('user_id',$user->id)->where('article_id',$article_id)->where('action','turn-score')->first();
          if($action_score){
            return  ['error'=>1,'message'=>'你已经打过分了！'];
          } else {
            $action_score = ArticleAction::create([
              'user_id' => $user->id,
              'action' => $action,
              'score' => $score,
              'article_id' => $article_id,
            ]);
          }
          return  ['error'=>0,'message'=>'评分成功！'];
          break;
      default:
        return  ['error'=>1,'message'=>'未知的操作类型！'];
    }
  }
}
